#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <error.h>
#include <string.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include <stdlib.h>
#include<unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

Log lg;

const static int default_backlog=5;//TODO

class TcpServer : public nocopy // 用于1不想让服务器被拷贝
{
public:
    TcpServer(uint16_t port)
        : _port(port),_isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        // sockfd本质就是文件描述符
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            lg.LogMessage(Fatal, "create socket error,errno code:%, error string:%s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Debug, "create socket success,sockfd:%d\n", _listen_sock);

        // 2.绑定套接字地址信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // bind
        int n = ::bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)); // 将套接字地址结构体绑定到套接字
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind err ,%d:%s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg.LogMessage(Debug, "bind success\n");

        //3.设置socket为监听状态，tcp特有的
        int m=listen(_listen_sock, default_backlog);
        if(m!=0)
        {
            lg.LogMessage(Fatal, "listen err ,%d:%s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen successs\n");

    }
    //TCP连接服务，是全双工通信的
    void serverice(int sockfd)
    {
        char buffer[1024];
        while(true)
        {
            size_t n=read(sockfd,buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]=0;
                cout<<"client say#  "<<buffer<<endl;

                string echo_string="server say#";
                echo_string+=buffer;
                write(sockfd,echo_string.c_str(),echo_string.size());
            }
            else if(n==0)//read如果返回值是0，表示读到了文件的结尾（对端关闭了）
            {
                lg.LogMessage(Info,"client close the connection\n");
                break;
            }
            else
            {
                lg.LogMessage(Error,"read socket error,errno code:%d,error string:%s\n",errno,strerror(errno));
                break;
            }
        }
    }
    void Start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            //4.获取用户连接
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sockfd=accept(_listen_sock,(struct sockaddr*)&peer,&len);
            if(sockfd<0)
            {
                lg.LogMessage(Warning,"accept socket error,errno code:%d,error string:%s\n",errno,strerror(errno));
                continue;
            }
            lg.LogMessage(Debug,"accept a new client,sockfd:%d\n",sockfd);

            //5.提供服务
            //v1
            serverice(sockfd);
            close(sockfd);
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listen_sock;//这个套接字主要用于监听
    //不是用于和client进行通信的
    bool _isrunning;
};